#!/usr/bin/env python3
"""
Generate Alembic migration script
生成数据库迁移脚本
"""

import os
import sys
from pathlib import Path

# 添加src到Python路径
sys.path.append(str(Path(__file__).parent.parent / "src"))

def generate_migration():
    """生成迁移脚本"""
    try:
        # 设置环境变量以避免配置加载问题
        os.environ["APP_ENV"] = "development"
        os.environ["DATABASE_URL"] = "postgresql+asyncpg://postgres:A123#@192.168.122.205:5432/media_create_db"
        os.environ["SECRET_KEY"] = "development-secret-key-for-migration-generation-only"
        os.environ["CORS_ORIGINS"] = "http://localhost:3000"
        
        # 导入必要的模块
        from alembic.config import Config
        from alembic import command
        from media_create.core.database import Base
        
        # 创建Alembic配置
        alembic_cfg = Config("alembic.ini")
        alembic_cfg.set_main_option("script_location", "alembic")
        alembic_cfg.set_main_option("sqlalchemy.url", os.environ["DATABASE_URL"])
        
        # 生成迁移脚本
        print("正在生成迁移脚本...")
        command.revision(
            alembic_cfg,
            autogenerate=True,
            message="Initial migration - create all core tables"
        )
        print("迁移脚本生成完成！")
        
    except Exception as e:
        print(f"生成迁移脚本时出错: {e}")
        import traceback
        traceback.print_exc()
        return False
    
    return True

if __name__ == "__main__":
    success = generate_migration()
    sys.exit(0 if success else 1)